package cn.ilikes.tools.hbase.jpa.persistences;

import java.util.Map;

import java.util.Properties;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceUnitUtil;
import javax.persistence.metamodel.Metamodel;

import org.slf4j.Logger;

import cn.ilikes.tools.hbase.jpa.JPAHbasePersistenUnitEnv;
import cn.ilikes.tools.hbase.jpa.SysConfigs;
import cn.ilikes.tools.hbase.jpa.SysConfigs.DataStoreType;
import cn.ilikes.tools.hbase.jpa.clients.AbClient;
import cn.ilikes.tools.hbase.jpa.clients.Client;
import cn.ilikes.tools.hbase.jpa.clients.ClientFactoryImple;
import cn.ilikes.tools.hbase.jpa.indexs.IndexClient;
import cn.ilikes.tools.hbase.jpa.indexs.JPAHBsaeDefultIndexClient;
import cn.ilikes.tools.hbase.jpa.metadatas.JPAHBasePersistenceUnitMetadata;
import cn.ilikes.tools.hbase.jpa.metadatas.sub.configs.Datastorefactory.DataStore;
import cn.ilikes.tools.logs.Loggerfactory;

public class DefaultJPAHBaseEntityManagerFactory extends JPAHBaseEntityManagerFactory {

	private static Logger logger = Loggerfactory.instance(DefaultJPAHBaseEntityManagerFactory.class);

	public DefaultJPAHBaseEntityManagerFactory(Properties properties, JPAHbasePersistenUnitEnv hbasePersistenUnitEnv) {
		super(hbasePersistenUnitEnv);
		Loggerfactory.info(logger, "create  persistence units name : " + hbasePersistenUnitEnv.getPersistenceUnitsName() + " Default JPA HBase Entity Manager Factory ");
	}

	private AbClient initClients() {

		JPAHBasePersistenceUnitMetadata hBasePersistenceUnitMetadata = (this.getHbasePersistenUnitEnv().gethBasePersistenceUnitMetadata());
		//索引
		IndexClient indexClient = new JPAHBsaeDefultIndexClient(hBasePersistenceUnitMetadata.getIndexfactory());
		//数据源
		DataStore dataStore = hBasePersistenceUnitMetadata.getDataStore();

		String jpaDialect = hBasePersistenceUnitMetadata.getProperties().getProperty(SysConfigs.jpa_dialect);

		DataStoreType dataStoreType = DataStoreType.valueOf(jpaDialect);

		dataStore.setDataStoreType(dataStoreType);

		AbClient clients = ClientFactoryImple.createClient(dataStore, indexClient, this.getHbasePersistenUnitEnv());

		return clients;
	}

	@Override
	public void close() {

		Loggerfactory.info(logger, "=============> DefaultJPAHBaseEntityManagerFactory  ; close  this not work ! ");
	}

	@Override
	public EntityManager createEntityManager() {

		return this.createEntityManager(null);
	}

	@Override
	public EntityManager createEntityManager(Map arg0) {

		if (Loggerfactory.isdebug(logger))
			Loggerfactory.debug(logger, " create entity manager ");
		AbClient clients = initClients();
		EntityManager entityManager = new JPAHBaseEntityManager(this.getHbasePersistenUnitEnv(), clients);

		return entityManager;

	}

	@Override
	public Metamodel getMetamodel() {

		return super.getMetamodel();
	}

	@Override
	public PersistenceUnitUtil getPersistenceUnitUtil() {

		return super.getPersistenceUnitUtil();
	}

	@Override
	public boolean isOpen() {

		return super.isOpen();
	}

}
